package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.util.BeanHelper;
import com.usian.common.util.JwtUtils;
import com.usian.model.user.dtos.AppLoginDto;
import com.usian.model.user.dtos.UserInfoDto;
import com.usian.user.entity.ApUser;
import com.usian.user.service.ApUserLoginService;
import com.usian.user.service.IApUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private IApUserService apUserService;


    /**
     * app端用户登录
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> login(AppLoginDto dto) {
          //1.参数校验
          if (dto==null){
              throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
          }
        //2.1先初始化userId为0，
        int userId=0;
        //创建封装数据得map集合
        Map<String,Object> map = new HashMap<>();

        //2.判断是登录操作还是未登录先看看
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {
            //根据手机号查询用户信息
            QueryWrapper<ApUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ApUser::getPhone,dto.getPhone());
            ApUser apUser = apUserService.getOne(queryWrapper);
            if (apUser == null) {
                throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"手机号错误");
            }
            //校验密码
            boolean b = passwordEncoder.matches(dto.getPassword(), apUser.getPassword());
            if (!b) {
                throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"密码错误");
            }
            //获取用户id
            userId = apUser.getId();
            //获取用户信息
            UserInfoDto userInfoDto = BeanHelper.copyProperties(apUser, UserInfoDto.class);
            map.put("user",userInfoDto);

        }else {
            //2设备号登录访问（未登录先看看）
            // 判断设备号是否存在
            if (StringUtils.isBlank(dto.getEquipmentId())) {
                throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"设备号不存在");
            }
        }

        //生成token，存入map集合
        String token = JwtUtils.generateTokenExpireInMinutes(userId, 60 * 24 * 7);
        map.put("token",token);
        return map;
    }
}
